package generic.no2;

import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Scanner;

public class ArraySwapperOriginal {
	public static <T extends Comparable<T>>
		boolean swap(T[] ts,T t1,T t2){
		T temp=null;
		int find=0,index_temp=0;
		for (int index=0;index<ts.length;index++){
			if(ts[index].compareTo(t1)==0)
				switch(find){
					case 0:
						temp=ts[index];
						find=1;index_temp=index;
						break;
					case 2:
						ts[index_temp]=ts[index];
						ts[index]=temp;
						for(T t:ts) System.out.println(t);
						return true;
					case 1:
						System.out.println("第一个元素出现多次");
						return false;
				}
			else if(ts[index].compareTo(t2)==0)
				switch (find){
					case 0:
						temp=ts[index];
						find=2; index_temp=index;
						break;
					case 1:
						ts[index_temp]=ts[index];
						ts[index]=temp;
						for(T t:ts) System.out.println(t);
						return true;
					case 2:
						System.out.println("第二个元素出现多次");
						return false;
				}
		}
		switch (find) {
			case 0:	System.out.println("两个元素均未找到");
			case 1:	System.out.println("第二个元素未找到");
			case 2:	System.out.println("第一个元素未找到");
			default:System.out.println("未知错误");
		}
		return false;
	}
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		LinkedList<Integer> linkedList = new LinkedList<>();
		System.out.println("请输入数组元素：(输入其他字符退出输入)");
		while (true) {
			try {
				linkedList.add(scanner.nextInt());
			} catch (InputMismatchException inputMismatchException) {
				scanner.next();
				break;
			}
		}
		System.out.println("请输入待交换的元素（2个）");
		while (true){
			try {
				if (!swap(linkedList.toArray(new Integer[0]),
						scanner.nextInt(),
						scanner.nextInt())) {
					System.out.println("交换失败，请重试");
					continue;
				}
				break;
			} catch (InputMismatchException inputMismatchException) {
				System.out.println("需输入两个数字");
			}
		}
	}
}
